from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from utils.goods import get_categories,get_contents
#定义类视图，获取 分类数据 和商品数据 然后进行 render的渲染
#我们到 goods.views.py文件定义一个类视图

class IndexView(View):

    def get(self,request):

        #这2个key是固定的
        context = {
          'categories': get_categories(),
          'contents': get_contents()
        }

        return render(request,'index.html',context = context)

###########################列表页面
from apps.goods.models import SKU
class ListSKUView(View):

    def get(self,request,category_id):
        #接收参数
        query_params = request.GET
        #2,提取
        ordering = query_params.get('ordering','-createtime')   #排序
        page_size = query_params.get('page_size',10)      #一页多少天记录
        page = query_params.get('page')               #第几页
        #3验证参数
        #4，查询数据排序
        skus = SKU.objects.filter(category=category_id).order_by(ordering)
        #4.3 查询的数据分页
        from django.core.paginator import Paginator
        #创建分页类
        #objet_list 查询结果集/列表
        #per_page 煤业多少天记录
        instance = Paginator(skus,page_size)

        #获取指定页数的数据
        per_page = instance.page(page)

        #获取总页数
        total =instance.num_pages

        #将对象列表转换为字典
        data_list = []
        for item in per_page.object_list:
            data_list.append({
                'id': item.id,
                'name': item.name,
                'price': item.price,
                'default_image_url': item.default_image.url  # 注意 调用url 因为要把图片 拼接 七牛云的外链
            })

        #面包屑数据
        from apps.goods.models import GoodsCategory
        from utils.goods import get_breadcrumb
        category = GoodsCategory.objects.get(id =category_id)
        breadcrumb = get_breadcrumb(category)

        #返回响应
        return JsonResponse({
            "code": 0,
            "errmsg": "ok",
            'breadcrumb':breadcrumb,
            "list": data_list,
            "count": total
        })

##############################热销数据
class HotSKUView(View):

    def get(self,request,category_id):

        skus = SKU.objects.filter(category=category_id).order_by('-sales')[:2]

        #将对象列表转换为字典
        data_list = []
        for item in skus:
            data_list.append({
                'id': item.id,
                'name': item.name,
                'price': item.price,
                'default_image_url': item.default_image.url  # 注意 调用url 因为要把图片 拼接 七牛云的外链
            })
        return JsonResponse({
            "code": "0",
            "errmsg": "OK",
            "hot_skus": data_list})

############################商品详情页
class DetailView(View):

    def get(self,request,sku_id):

        try:
            sku = SKU.objects.get(id = sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'没有此商品'})

        #获取分类数据
        from utils.goods import get_categories

        categories = get_categories()

        #获取面包屑数据
        from utils.goods import get_breadcrumb
        breadcrumb = get_breadcrumb(sku.category)

        #获取规格和规格选项
        from utils.goods import get_goods_specs
        specs = get_goods_specs(sku)

        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': specs,
        }

        return render(request, 'detail.html', context=context)

############################商品访问量
from apps.goods.models import GoodsCategory,GoodsVisitCount
from datetime import date
class CategoryVisitView(View):

    def post(self,request,category_id):
        #1. 根据分类id查询数据

        try:
            category = GoodsCategory.objects.get(id = category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'分类信息错误'})

        #根据统计模型，查询当前分类记录
        today = date.today()

        try:
            gvc = GoodsVisitCount.objects.get(category=category,
                                                 date=today)
        except GoodsVisitCount.DoesNotExist:
            #如果不存在，则新增
            GoodsVisitCount.objects.create(category=category, count=1,date=today)
        else:
            #4.存在，访问量+1
            gvc.count += 1
            gvc.save()

        return JsonResponse({'code': 0, 'errmsg': 'ok'})

from haystack.views import SearchView
class MySearchView(SearchView):

    def create_response(self):
        # haystack 会接收 search中的请求.帮助我们对接es
        # 这个时候的数据已经获取到了
        # 在哪里呢?? context
        context = self.get_context()

        page = context.get('page')

        object_list = page.object_list

        data_list = []
        # 对对象列表进行遍历
        for item in object_list:
            # item.object 相当于 sku实例对象
            # item.object.id
            data_list.append({
                'id': item.object.id,
                'name': item.object.name,
                'price': item.object.price,
                'default_image_url': item.object.default_image.url,
                "searchkey": context.get('query'),  # 搜索的关键字
                "page_size": context.get('paginator').num_pages,
                "count": context.get('paginator').count
            })

        return JsonResponse(data_list, safe=False)



